package ru.common;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;

/**
 *
 */
public class StatementEmailServiceImpl implements StatementEmailService {
    private String from, replyTo;
    private JavaMailSenderImpl javaMailSender;

    @Override
    public void send(StatementEmail email) throws Exception {
        send(email, from, replyTo);
    }

    /**
     * @return the from
     */
    public String getFrom() {
        return from;
    }

    /**
     * @param from the from to set
     */
    @Required
    public void setFrom(String from) {
        this.from = from;
    }

    public String getReplyTo() {
        return replyTo;
    }

    @Required
    public void setReplyTo(String replyTo) {
        this.replyTo = replyTo;
    }

    /**
     * @return the javaMailSender
     */
    public JavaMailSenderImpl getJavaMailSender() {
        return javaMailSender;
    }

    /**
     * @param javaMailSender the javaMailSender to set
     */
    public void setJavaMailSender(JavaMailSenderImpl javaMailSender) {
        this.javaMailSender = javaMailSender;
    }

    @Override
    public void send(StatementEmail email, String addressfrom, String replyto) throws Exception {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(addressfrom);
        for (String to : email.getTo()) {
            helper.addTo(to);
        }
        for (String cc : email.getCc()) {
            helper.addCc(cc);
        }
        for (String bcc : email.getBcc()) {
            helper.addBcc(bcc);
        }
        helper.setReplyTo(replyto);
        helper.setSubject(email.getSubject());
        helper.setText(email.getBody(), email.isHTML());
        for (StatementEmail.Attachment attachment : email.getAttachments()) {
            helper.addAttachment(attachment.getName(), attachment.getSource());
        }
        javaMailSender.send(message);
    }

}
